package org.example.util;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.example.common.bean.ResponseBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Excel 工具类
 * 注意swagger页面下载文件报错：Excel无法打开文件xxx，因为文件格式或文件扩展名无效。请确定文件未损坏
 *
 * @author 芋道源码
 */
public class ExcelUtils {
    /**
     * 动态表头
     * 将列表以 Excel 响应给前端
     *
     * @param response  响应
     * @param filename  文件名
     * @param sheetName Excel sheet 名
     * @param heads     Excel head 头  可使用LinkedHashMap保持排序, key为data中map的字段key值, value为excel的表头
     * @param data      数据列表，一个map为excel中的一行数据
     * @throws IOException 写入失败的情况
     * 注意swagger页面下载文件报错：Excel无法打开文件xxx，因为文件格式或文件扩展名无效。请确定文件未损坏
     */
    public static <T> void write(HttpServletResponse response, String filename, String sheetName,
                                 Map<String, String> heads, List<Map<String, Object>> data) throws IOException {
        write(response, filename, sheetName, heads.values().toArray(new String[0]), heads.keySet().toArray(new String[0]), data);
    }


    /**
     * 动态表头
     * 将列表以 Excel 响应给前端
     *
     * @param response   响应
     * @param filename   文件名
     * @param sheetName  Excel sheet 名
     * @param heads      Excel head 头  LinkedHashMap保持排序
     * @param fieldInMap head中与map中的key字段一致
     * @param data       数据列表
     * @throws IOException 写入失败的情况
     * 注意swagger页面下载文件报错：Excel无法打开文件xxx，因为文件格式或文件扩展名无效。请确定文件未损坏
     */
    public static <T> void write(HttpServletResponse response, String filename, String sheetName,
                                 String[] heads, String[] fieldInMap, List<Map<String, Object>> data) throws IOException {
        List<List<String>> headsList = ListUtils.newArrayList();
        //excel表头
        Arrays.stream(heads).forEach(head -> {
            List<String> headList = ListUtils.newArrayList();
            headList.add(head);
            headsList.add(headList);
        });



        //excel数据
        List<List<Object>> datasList = ListUtils.newArrayList();
        data.forEach(dataMap -> {
            List<Object> dataList = ListUtils.newArrayList();
            Arrays.stream(fieldInMap).forEach(field -> {
                dataList.add(dataMap.getOrDefault(field, StringUtils.EMPTY));
            });
            datasList.add(dataList);
        });

        write(response, filename, sheetName, headsList, datasList, null);
    }

    /**
     * 动态表头
     * 将列表以 Excel 响应给前端
     *
     * @param response                响应
     * @param filename                文件名
     * @param sheetName               Excel sheet 名
     * @param head                    Excel head 头
     * @param data                    数据列表
     * @param includeColumnFieldNames 指定导出的列, 为空的情况下，默认导出所有列
     * @throws IOException 写入失败的情况
     * 注意swagger页面下载文件报错：Excel无法打开文件xxx，因为文件格式或文件扩展名无效。请确定文件未损坏
     */
    public static <T> void write(HttpServletResponse response, String filename, String sheetName,
                                 List<List<String>> head, List<List<Object>> data, Collection<String> includeColumnFieldNames) throws IOException {

        setExcelHeader(response, filename);
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            writeExcel(response.getOutputStream(), sheetName, head, data, includeColumnFieldNames);
        } catch (Exception e) {
            failedHeader(response, e.getMessage());
        }
    }


    /**
     * 将列表以 Excel 响应给前端
     *
     * @param response                响应
     * @param filename                文件名
     * @param sheetName               Excel sheet 名
     * @param head                    Excel head 头
     * @param data                    数据列表
     * @param <T>                     泛型，保证 head 和 data 类型的一致性
     * @param includeColumnFieldNames 指定导出的列, 为空的情况下，默认导出所有列
     * @throws IOException 写入失败的情况
     * 注意swagger页面下载文件报错：Excel无法打开文件xxx，因为文件格式或文件扩展名无效。请确定文件未损坏
     */
    public static <T> void write(HttpServletResponse response, String filename, String sheetName,
                                 Class<T> head, List<T> data, Collection<String> includeColumnFieldNames) throws IOException {
        setExcelHeader(response, filename);
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            writeExcel(response.getOutputStream(), sheetName, head, data, includeColumnFieldNames);
        } catch (Exception e) {
            failedHeader(response, e.getMessage());
        }
    }

    public static <T> void write(HttpServletResponse response, String filename, String sheetName,
                                 Class<T> head, List<T> data) throws IOException {
        write(response, filename, sheetName, head, data, null);
    }


    /**
     * 将列表以 Excel 响应给前端
     *
     * @param outputStream            输出流
     * @param sheetName               Excel sheet 名
     * @param head                    Excel head 头
     * @param data                    数据列表
     * @param <T>                     泛型，保证 head 和 data 类型的一致性
     * @param includeColumnFieldNames 指定导出的列, 为空的情况下，默认导出所有列
     * 注意swagger页面下载文件报错：Excel无法打开文件xxx，因为文件格式或文件扩展名无效。请确定文件未损坏
     */
    public static <T> void writeExcel(OutputStream outputStream, String sheetName,
                                      Class<T> head, List<T> data, Collection<String> includeColumnFieldNames) {

        ExcelWriterBuilder excelWriterBuilder = buildExcelWriter(outputStream, head, includeColumnFieldNames);
        ExcelWriterSheetBuilder excelWriterSheetBuilder = excelWriterBuilder.sheet(sheetName);
        excelWriterSheetBuilder.doWrite(data);
    }

    /**
     * 动态表头
     * 将列表以 Excel 响应给前端
     *
     * @param outputStream            响应
     * @param sheetName               Excel sheet 名
     * @param head                    Excel head 头
     * @param data                    数据列表
     * @param includeColumnFieldNames 指定导出的列, 为空的情况下，默认导出所有列
     * @throws IOException 写入失败的情况
     * 注意swagger页面下载文件报错：Excel无法打开文件xxx，因为文件格式或文件扩展名无效。请确定文件未损坏
     */
    public static void writeExcel(OutputStream outputStream, String sheetName,
                                  List<List<String>> head, List<List<Object>> data, Collection<String> includeColumnFieldNames) throws IOException {

        ExcelWriterBuilder excelWriterBuilder = buildExcelWriter(outputStream, head, includeColumnFieldNames);
        ExcelWriterSheetBuilder excelWriterSheetBuilder = excelWriterBuilder.sheet(sheetName);
        excelWriterSheetBuilder.doWrite(data);
    }

    /**
     * 将列表以 Excel 响应给前端
     *
     * @param outputStream            文件流
     * @param head                    Excel head 头
     * @param includeColumnFieldNames 指定导出的列, 为空的情况下，默认导出所有列
     */
    public static ExcelWriterBuilder buildExcelWriter(OutputStream outputStream, List<List<String>> head, Collection<String> includeColumnFieldNames) {
        // 输出 Excel
        ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(outputStream)
                .head(head)
                // 不要自动关闭，交给 Servlet 自己处理
                .autoCloseStream(false)
                // 基于 column 长度，自动适配。最大 255 宽度
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy());
        if (CollectionUtil.isNotEmpty(includeColumnFieldNames)) {
            excelWriterBuilder.includeColumnFieldNames(includeColumnFieldNames);
        }

        return excelWriterBuilder;
    }

    /**
     * 将列表以 Excel 响应给前端
     *
     * @param outputStream            文件流
     * @param head                    Excel head 头
     * @param includeColumnFieldNames 指定导出的列, 为空的情况下，默认导出所有列
     */
    public static <T> ExcelWriterBuilder buildExcelWriter(OutputStream outputStream, Class<T> head, Collection<String> includeColumnFieldNames) {
        // 输出 Excel
        ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(outputStream)
                .head(head)
                // 不要自动关闭，交给 Servlet 自己处理
                .autoCloseStream(false)
                // 基于 column 长度，自动适配。最大 255 宽度
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy());
        if (CollectionUtil.isNotEmpty(includeColumnFieldNames)) {
            excelWriterBuilder.includeColumnFieldNames(includeColumnFieldNames);
        }

        return excelWriterBuilder;
    }


    public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
        return read(file.getInputStream(), head);
    }

    public static <T> List<T> read(InputStream inputStream, Class<T> head) {
        return read(inputStream, head, null, 0);
    }

    public static <T> List<T> read(InputStream inputStream, Class<T> head, Integer headRowNumber) {
        return read(inputStream, head, null, headRowNumber);
    }

    public static <T, V> List<T> read(InputStream inputStream, Class<T> head, ReadListener<V> readListener) {
        return read(inputStream, head, readListener, 0);
    }

    /**
     * 读取数据.
     *
     * @param inputStream   输入流
     * @param head          表头泛型
     * @param readListener  读取监听器
     * @param headRowNumber 请求头的行数
     *                      0 - This Sheet has no head ,since the first row are the data
     *                      1 - This Sheet has one row head , this is the default
     *                      2 - This Sheet has two row head ,since the third row is the data
     * @param <T>           泛型，保证 head 和 data 类型的一致性
     * @return List 数据列表, 格式和head表头一致
     */
    public static <T, V> List<T> read(InputStream inputStream, Class<T> head, ReadListener<V> readListener, Integer headRowNumber) {
        return EasyExcel.read(inputStream, head, readListener)
                .headRowNumber(headRowNumber)
                // 不要自动关闭，交给 Servlet 自己处理
                .autoCloseStream(false)
                .doReadAllSync();
    }

    public static void setExcelHeader(HttpServletResponse response, String filename) throws UnsupportedEncodingException {
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
    }

    public static void failedHeader(HttpServletResponse response, String message) throws IOException {
        // 重置response
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(ResponseBean.failed(message));
    }
}
